#!/usr/bin/env python
"""
-->
FileContent = "Defines the content you like write in the csv-file."
-->

-->
CSVFileInfo = "Defines the place where do you like to save the csv-file."
FilePath = {'type': "System.String", 'description': "Path of the csv file you like to work with.", 'validation': "IsFile"}
Seperator = {'type': "System.String", 'description': "The delimiter which split the data. In most cases comma or semicolon.", 'defaultValue': ";"}
CreateHeader = {'type': "System.Boolean", 'description': If true the csv-file will generate with header-informations.", 'defaultValue': "true"}
-->


"""

#http://openbook.galileocomputing.de/python/python_kapitel_19_005.htm#mj068051f9093b3bd5bfc5628714320a14	

from MyClever.Lib import MissionPlugin
import csv

__author__ = "Mathias Mielitz"
__copyright__ = "Copyright 2012, MyCleverFriend"
__credits__ = ["Mathias Mielitz"]
__license__ = "GPL"
__version__ = "1.0.0.0"
__maintainer__ = "Mathias Mielitz"
__email__ = "m.mielitz@adrabbit.de"
__status__ = "Production"
__description__ = "Writes the given data in a csv-file."

class WriteCSV(MissionPlugin):
	def Work(self):

		csvInfoPackage = self.GetDataReader("CSVFileInfo")
		while csvInfoPackage.Read():
			self.AddNewLoggingMessage("CSVFileInfo", "write csv-file: " + csvInfoPackage["FilePath"].ToString());			

			file = open(csvInfoPackage["FilePath"].ToString(), "wb");
			writer = csv.writer(file, delimiter=csvInfoPackage["Seperator"].ToString()) 
			columnDefinitions = self.GetColumnNames("FileContent");

			data = [];

			# create Headers
			headerRow = [];
			if ("true" == csvInfoPackage["CreateHeader"].ToString().lower()):
				for columnOn in columnDefinitions:
					headerRow.append(columnOn[0]);
				data.append(headerRow);

			fileContentPackage = self.GetDataReader("FileContent")
			while fileContentPackage.Read():
				newRow = [];
				for columnOn in columnDefinitions:
					newRow.append(fileContentPackage[columnOn[0]]);
				data.append(newRow);

			writer.writerows(data);
			file.close();